package framework.webclient;

import java.util.Map;

import javax.ws.rs.core.Cookie;


import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;


public class RestSocketImpl implements RestSocket {

	private Client client;
	private String resourceNode;
	private Cookie cookie;


	public RestSocketImpl(Cookie authCookie, String resourceNode) {
		initialize(authCookie, resourceNode);
	}

	private void initialize(Cookie authCookie, String resourceNode) {
		client = Client.create();
		client.setConnectTimeout(30*1000);
		client.setReadTimeout(30*1000);
		client.setFollowRedirects(Boolean.TRUE);
		this.resourceNode = resourceNode;
		this.cookie = authCookie;
	}
	
	public RestSocketImpl(String resourceNode) {
		initialize(null, resourceNode);
	}
	@Override
	public <M> M get(String path, Class<M> cls, Map<String, String> parameters) {
		WebResource webResource = client.resource(resourceNode).path(path);
		if (parameters != null) {
			for (String key : parameters.keySet()) {
				webResource = webResource.queryParam(key, parameters.get(key));
			}
		}
		return webResource.get(cls);
	}

	@Override
	public <M> M post(String path, Object object, Class<M> cls) {
		WebResource webResource = client.resource(resourceNode).path(path);
		return webResource.cookie(cookie).post(cls, object);
	}

	@Override
	public <M> M put(String path, Object object, Class<M> cls) {
		WebResource webResource = client.resource(resourceNode).path(path);
		return webResource.cookie(cookie).put(cls, object);
	}

	@Override
	public <M> M delete(String path, Class<M> cls,
			Map<String, String> parameters) {
		WebResource webResource = client.resource(resourceNode).path(path);
		if (parameters != null) {
			for (String key : parameters.keySet()) {
				webResource = webResource.queryParam(key, parameters.get(key));
			}
		}
		return webResource.cookie(cookie).delete(cls);
	}

}
